package cn.buildoncloud.labor.workermanapplet.business.modules.services.impl;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.WorkerTeamService;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.common.base.service.BaseServiceImpl;
import cn.buildoncloud.labor.workermanapplet.common.page.Pagination;
import cn.buildoncloud.labor.workermanapplet.dto.TeamInProjectDTO;
import cn.buildoncloud.labor.workermanapplet.dto.WorkerManDTO;
import cn.buildoncloud.labor.workermanapplet.dto.WorkerTeamDTO;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import cn.buildoncloud.labor.workermanapplet.util.StringUtil;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: cn.buildoncloud.labor.workermanapplet.business.modules.services.impl
 * Created by CuiZibo on 2018/11/6 18:33
 */
@Service
public class WorkerTeamServiceImpl extends BaseServiceImpl<Map> implements WorkerTeamService {

    public WorkerTeamServiceImpl(Dao dao) {
        super(dao);
        this.dao = dao;
    }

    private Dao dao;

    @Value("${webSystemIP}")
    private String webSystemIP;

    /**
     * 模糊查询该项目中已经进场的 班组列表
     *
     * @param projectId
     * @param key
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public Pagination fuzzyQueryWorkerTeam(String projectId, String key, Integer pageNumber, Integer pageSize) {

        StringBuffer sb = new StringBuffer();
        sb.append("SELECT CONCAT(t3.id,'') tId, t3.`name` tName, t3.team_leader_name tlName, t3.team_leader_tel tlTel, ");
        sb.append("GROUP_CONCAT( DISTINCT CONCAT(t5.`name`, '-', t6.`name`) SEPARATOR ',' ) workClasses,COUNT(DISTINCT t4.worker_man_id) count_ ");
        sb.append("FROM bi_re_workerteam_project t1 ");
        sb.append("LEFT JOIN bi_re_workerteam_project_entend t2 ON t1.id = t2.reWorker_team_and_projectid ");
        sb.append("LEFT JOIN bi_workerteam t3 ON t1.worker_team_id = t3.id ");
        sb.append("LEFT JOIN bi_re_workman_and_teamproject t4 ON t4.reWorker_team_and_projectid = t1.id AND t4.workman_out_date IS NULL ");
        sb.append("LEFT JOIN sys_work_class t5 ON t5.id = t2.work_class_id ");
        sb.append("LEFT JOIN sys_work_type t6 ON t6.id = t2.work_type_id ");
        sb.append("WHERE t1.out_date IS NULL AND t1.project_id = @projectId ");
        if (StringUtil.isNotBlank(key)) {
            sb.append("AND t1.worker_team_id IN ( SELECT t.id FROM `bi_workerteam` t WHERE t. NAME LIKE @key OR t.team_leader_name LIKE @key OR t.team_leader_tel LIKE @key ) ");
        }
        sb.append("GROUP BY t1.id ORDER BY count_ DESC  ");
        Sql sql = Sqls.create(sb.toString());
        if (StringUtil.isNotBlank(key)) {
            sql.setParam("key", "%" + key + "%");
        }
        sql.setParam("projectId", projectId);
//                .setCallback((conn, rs, sql1) -> {
//                    List<TeamInProjectDTO> list = new ArrayList<>();
//                    while (rs.next()) {
//                        TeamInProjectDTO team = new TeamInProjectDTO();
//                        team.setTeamId(rs.getString("tId"));
//                        team.setTeamName(rs.getString("tName"));
//                        team.setTeamLeaderName(rs.getString("tlName"));
//                        team.setTeamLeaderTel(rs.getString("tlTel"));
//                        team.setWorkClassAndworkTypeNameStr(rs.getString("workClasses"));
//                        team.setEnterProjectCount(rs.getInt("count_"));
//                        list.add(team);
//                    }
//                    return list;
//                });
//        dao.execute(sql);
//        List<TeamInProjectDTO> list = sql.getList(TeamInProjectDTO.class);

        return this.listPage(pageNumber,pageSize,sql);
    }

    /**
     * 班组详情，已进场信息为标准
     *
     * @param projectId
     * @param workerTeamId
     * @return
     */
    @Override
    public TeamInProjectDTO queryWorkerTeamInfoByIdAndProjectId(String projectId, String workerTeamId) {

        TeamInProjectDTO teamInProjectDTO = new TeamInProjectDTO();
        StringBuffer sb = new StringBuffer();
       sb.append("SELECT CONCAT(t1.id, '') tId, t1.`name` tName, t1.team_leader_name tlName, t1.team_leader_tel tlTel, t2.in_date tInDate, IFNULL( t7.`name`, '无所属劳务公司') laborName, GROUP_CONCAT( DISTINCT CONCAT(t4.`name`, '-', t5.`name`) SEPARATOR ',' ) workClasses, COUNT(DISTINCT t6.worker_man_id) inCount, COUNT(DISTINCT t8.worker_man_id) allCount ")
               .append("FROM bi_workerteam t1 ")
               .append("LEFT JOIN bi_re_workerteam_project t2 ON t2.worker_team_id = t1.id AND t2.project_id = @projectId  ")
               .append("LEFT JOIN bi_re_workerteam_project_entend t3 ON t3.reWorker_team_and_projectid = t2.id  ")
               .append("LEFT JOIN sys_work_class t4 ON t4.id = t3.work_class_id LEFT JOIN sys_work_type t5 ON t5.id = t3.work_type_id ")
               .append("LEFT JOIN bi_re_workman_and_teamproject t8 ON t8.reWorker_team_and_projectid = t2.id  ")
               .append("LEFT JOIN bi_re_workman_and_teamproject t6 ON t6.reWorker_team_and_projectid = t2.id AND t6.workman_out_date IS NULL  ")
               .append("LEFT JOIN bi_labor_service_company t7 ON t7.id = t1.labor_service_company_id WHERE t1.id = @workerTeamId  ");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("projectId", projectId)
                .setParam("workerTeamId", workerTeamId)
                .setCallback((conn, rs, sql1) -> {
                    List<TeamInProjectDTO> list = new ArrayList<>();
                    while (rs.next()) {
                        TeamInProjectDTO team = new TeamInProjectDTO();
                        team.setTeamId(rs.getString("tId"));
                        team.setTeamName(rs.getString("tName"));
                        team.setTeamLeaderName(rs.getString("tlName"));
                        team.setTeamLeaderTel(rs.getString("tlTel"));
                        team.setWorkClassAndworkTypeNameStr(rs.getString("workClasses"));
                        team.setLaborServiceCompanyName(rs.getString("laborName"));
                        team.setEnterProjectCount(rs.getInt("inCount"));
                        team.setEnterDate(rs.getDate("tInDate"));
                        team.setTotalCount(rs.getInt("allCount"));
                        list.add(team);
                    }
                    return list;
                });
        dao.execute(sql);
        List<TeamInProjectDTO> list = sql.getList(TeamInProjectDTO.class);
        list = list == null ? new ArrayList<>() : list;
        if (list.size() == 0)
            return null;
        teamInProjectDTO = list.get(0);

        return teamInProjectDTO;
    }

    /**
     * 查询已进场班组的详细信息，班组详情 参建项目 班组成员
     *
     * @param workerTeamId
     * @param projectId
     * @param allOrIn
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public TeamInProjectDTO queryWorkerTeamInfoById(String workerTeamId, String projectId, String allOrIn, Integer pageNumber, Integer pageSize) {
        TeamInProjectDTO teamInProjectDTO = new TeamInProjectDTO();
        //班组详情
        teamInProjectDTO = queryWorkerTeamInfoByIdAndProjectId(projectId, workerTeamId);
        //班组中所有的工友
        List<WorkerManDTO> workerManDTOS = queryWorkerManInTheTeam(projectId, workerTeamId);
        //班组的历史参建项目
        List<Map> porjectList = getHistoryPorjectByWorkerTeamId(workerTeamId);
        // 新增分页 + 排序
        Pagination pagination = getHistoryPorjectByWorkerTeamIdByPage(workerTeamId, pageNumber, pageSize);
        teamInProjectDTO.setWorkerManList(workerManDTOS);
        teamInProjectDTO.setInvolvedProjectList(porjectList);
        //分页
        teamInProjectDTO.setInvolvedProjectListByPage(pagination);
        return teamInProjectDTO;
    }

    /**
     * 通过班组长身份证号查询班组信息
     *
     * @param idCardNo
     * @return
     */
    @Override
    public WorkerTeamDTO queryWorkerTeamInfoByIdCardNo(String idCardNo) {

        WorkerTeamDTO team = new WorkerTeamDTO();
        StringBuffer sb = new StringBuffer("SELECT CONCAT(t1.id,'') tId ,t1.`name` tName,t1.team_leader_tel tlTel,CONCAT(t1.labor_service_company_id,'') laborId,t2.`name` labornName,t1.material_is materialIs,t1.bank_account,t1.open_account_bank,t1.worker_count FROM `bi_workerteam` t1 LEFT JOIN bi_labor_service_company t2 ON t2.id = t1.labor_service_company_id WHERE t1.id_card_no = @idCardNo");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("idCardNo", idCardNo)
                .setCallback((conn, rs, sql1) -> {
                    List<WorkerTeamDTO> list = new ArrayList<>();
                    while (rs.next()) {
                        WorkerTeamDTO workerTeamDTO = new WorkerTeamDTO();
                        workerTeamDTO.setTeamId(rs.getString("tId"));
                        workerTeamDTO.setTeamName(rs.getString("tName"));
                        workerTeamDTO.setTeamLeaderTel(rs.getString("tlTel"));
                        workerTeamDTO.setLaborServiceCompanyId(rs.getString("laborId"));
                        workerTeamDTO.setLaborServiceCompanyName(rs.getString("labornName"));
                        workerTeamDTO.setMaterialIs(rs.getInt("materialIs"));
                        workerTeamDTO.setBankAccount(rs.getString("bank_account"));
                        workerTeamDTO.setOpenAccountBank(rs.getString("open_account_bank"));
                        workerTeamDTO.setWorkerCount(rs.getInt("worker_count"));
                        list.add(workerTeamDTO);
                    }
                    return list;
                });
        dao.execute(sql);
        List<WorkerTeamDTO> list = sql.getList(WorkerTeamDTO.class);
        if (list != null && list.size() > 0) {
            team = list.get(0);
        }
        return team;

    }

    /**
     * 调用web端创建班组接口
     *
     * @param createTeamParameterMap
     * @return
     */
    @Override
    public String createWorkerTeam(Map createTeamParameterMap) {

        String s = HttpUtil.post(webSystemIP + "/business/workerteam/addWorkerTeam", createTeamParameterMap, 1000 * 10);
        Result result = Json.fromJson(Result.class, s);
        if (result.getCode() == 0 && result.getData() != null) {
            List<Map<String, Object>> resultDataList = (List<Map<String, Object>>) result.getData();
            if (resultDataList != null && resultDataList.size() > 0) {
                Map<String, Object> resultData = resultDataList.get(0);
                if (resultData.containsKey("id")) {
                    return (String) resultData.get("id");
                }
            }
        }
        return null;
    }

    /**
     * 调用web端进场接口
     *
     * @param enterProjectParameterMap
     * @return
     */
    @Override
    public int enterPorject(Map enterProjectParameterMap) {

        String s = HttpUtil.post(webSystemIP + "/business/workerteam/createWorkerTeamAndProject", enterProjectParameterMap, 1000 * 30);
        Result result2 = Json.fromJson(Result.class, s);
        return result2.getCode();
    }

    /**
     * 查询班组下所有的工友
     *
     * @param projectId
     * @param workerTeamId
     * @return
     */
    private List<WorkerManDTO> queryWorkerManInTheTeam(String projectId, String workerTeamId) {

        StringBuffer sb = new StringBuffer("SELECT DISTINCT t3.id,t3.`name`,CONCAT(t3.head_photo_id, '') head_photo_id,t3.tel,CONCAT(t4.`name`, '-', t5.`name`) workClass,CASE WHEN t2.workman_out_date IS NULL THEN '在场' ELSE '已退场' END state " +
                "FROM bi_re_workman_and_teamproject t2 LEFT JOIN bi_workerman t3 ON t3.id = t2.worker_man_id LEFT JOIN sys_work_class t4 ON t4.id = t2.work_class_id LEFT JOIN sys_work_type t5 ON t5.id = t2.work_type_id " +
                "WHERE t2.worker_man_id IN (SELECT worker_man_id FROM bi_re_workerteam_and_workerman t1 WHERE t1.worker_team_id = @workerTeamId)AND t2.project_id = @projectId " +
                "AND t2.reWorker_team_and_projectid = (SELECT t6.id FROM bi_re_workerteam_project t6 WHERE t6.project_id = @projectId AND t6.worker_team_id = @workerTeamId) ");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("workerTeamId", workerTeamId).setParam("projectId", projectId).
                setCallback((conn, rs, sql1) -> {
                    List<WorkerManDTO> list = new ArrayList<>();
                    while (rs.next()) {
                        WorkerManDTO workerManDTO = new WorkerManDTO();
                        workerManDTO.setManId(rs.getLong("id") + "");
                        workerManDTO.setManName(rs.getString("name"));
                        workerManDTO.setManTel(rs.getString("tel"));
                        workerManDTO.setHeadPhotoId(rs.getString("head_photo_id"));
                        workerManDTO.setWorkClassAndworkTypeNameStr(rs.getString("workClass"));
                        workerManDTO.setProjectState(rs.getString("state"));
                        list.add(workerManDTO);
                    }
                    return list;
                });
        dao.execute(sql);
        List<WorkerManDTO> list = sql.getList(WorkerManDTO.class);
        if (list != null && list.size() > 1) {

        }
        for (int i = 0; i < list.size(); i++) {
            for (int j = i + 1; j < list.size(); j++) {
                if (list.get(i).getManId().equals(list.get(j).getManId())) {
                    if(list.get(i).getProjectState().equals("已退场")){
                        list.remove(i);
                    }else if(list.get(i).getProjectState().equals("在场")){
                        list.remove(j);
                    }
                }

            }
        }

        return list;
    }

    /**
     * 查询班组的历史参建项目  分页+排序
     *
     * @param workerTeamId
     * @return
     */
    private List<Map> getHistoryPorjectByWorkerTeamId(String workerTeamId) {

        StringBuffer sb = new StringBuffer("SELECT CONCAT(t1.in_date, ' 至 ', IFNULL(t1.out_date,'现在')) workingTime , t2.`name` pName, t1.have_bad_record, t1.bad_record_note, t1.evaluate, t1.score FROM `bi_re_workerteam_project` t1 LEFT JOIN bi_project t2 ON t2.id = t1.project_id WHERE t1.worker_team_id = @workerTeamId  order by t1.id desc");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("workerTeamId", workerTeamId).
                setCallback((conn, rs, sql1) -> {
                    List<Map> list = new ArrayList<>();
                    while (rs.next()) {
                        Map map = new HashMap();
                        map.put("workingTime", rs.getString("workingTime"));
                        map.put("pName", rs.getString("pName"));
                        map.put("haveBadRecord", rs.getInt("have_bad_record"));
                        map.put("badRecordNote", rs.getString("bad_record_note"));
                        map.put("evaluate", rs.getString("evaluate"));
                        map.put("starLevel", rs.getInt("score"));
                        list.add(map);
                    }
                    return list;
                });
                dao.execute(sql);


        List<Map> list = sql.getList(Map.class);

        return  list;
    }

    /**
     * 查询班组的历史参建项目  分页+排序
     *@create 2019/1/14 12:28
     * @param workerTeamId
     * @param pageNo
     * @param pageSize
     * @return
     */
    private Pagination getHistoryPorjectByWorkerTeamIdByPage(String workerTeamId, Integer pageNo, Integer pageSize) {
        StringBuffer sb = new StringBuffer("SELECT CONCAT(t1.in_date, ' 至 ', IFNULL(t1.out_date,'现在')) workingTime , t2.`name` pName, t1.have_bad_record, t1.bad_record_note, t1.evaluate, t1.score FROM `bi_re_workerteam_project` t1 LEFT JOIN bi_project t2 ON t2.id = t1.project_id WHERE t1.worker_team_id = @workerTeamId  order by t1.id desc");
        Sql sql = Sqls.create(sb.toString());
        sql.setParam("workerTeamId", workerTeamId);

        Pagination pagination = this.listPage(pageNo, pageSize, sql);
        return  pagination;
    }
}
